<?php

namespace app\admin\controller;

use think\Lang;
use app\common\model\Goodsclass;
use app\common\model\Waybill;
use app\service\GoodsService;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Projectorder extends AdminControl
{

    const EXPORT_SIZE = 1000;

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/vrorder.lang.php');
    }

    public function index()
    {
        $order_model = model('order');
        $condition = array();

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['order_sn'] = $order_sn;
        }

        $project_name = input('param.project_name');
        if ($project_name) {
            $condition['project_name'] = array('like', '%' . $project_name . '%');
        }
        $order_status = input('param.order_status');
        if ($order_status) {
            $condition['order_status'] = $order_status;
        }

        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }
        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['buyer_name'] = $buyer_name;
        }

        // $condition['op.is_cancel'] = 0;
        // $condition['o.order_state'] = array('lt',30); 
        // $order_list = $order_model->get_OrderprojectList($condition, 10);
        $condition['order_state'] = array('in', '10,20');
        $order_list = $order_model->get_ProjectorderList($condition, 10);

        $this->assign('order_status', ['0' => '待付款', '10' => '未付款', '20' => '已付款', '30' => '已发货', '40' => '已收货', '50' => '已取消', '55' => '已作废', '60' => '已发货']);
        //        订单状态：0:已取消 10:未付款 20:已付款 30:已发货 40:已收货
        $this->assign('show_page', $order_model->page_info->render());

        $this->assign('order_list', $order_list);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('index');

        return $this->fetch('index');
    }

    public function index2()
    {
        $order_model = model('order');
        $condition = array();

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['order_sn'] = $order_sn;
        }

        $project_name = input('param.project_name');
        if ($project_name) {
            $condition['project_name'] = array('like', '%' . $project_name . '%');
        }
        $order_status = input('param.order_status');
        if ($order_status) {
            $condition['order_status'] = $order_status;
        }

        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }
        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['buyer_name'] = $buyer_name;
        }
        //        $condition['ds_orderproject.is_cancel'] = 0;
        $condition['order_state'] = array('not in', '10,20');
        // $order_list = $order_model->get_OrderprojectList($condition, 10);
        
        $order_list = $order_model->get_ProjectorderList($condition, 10);

        $this->assign('order_status', ['0' => '已取消', '10' => '未付款', '20' => '已付款', '30' => '已收货', '40' => '已完成', '50' => '已退款', '55' => '已作废', '60' => '已发货']);
        //        订单状态：0:已取消 10:未付款 20:已付款 30:已发货 40:已收货
        $this->assign('show_page', $order_model->page_info->render());

        $this->assign('order_list', $order_list);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('index2');

        return $this->fetch('index2');
    }


    //项目定制订单详情
    public function projectorder_list()
    {
        $order_id = intval(input('param.order_id'));
        // $project_order = db('orderproject')->alias('op')
        //       ->join('order o','o.orderproject_id=op.order_id')
        //       ->field('op.*,o.order_state as zhu_order_state,o.orderproject_id')
        //       ->where('op.order_id', $order_id)->find();
        $project_order = db('orderproject')->alias('op')
            ->where('order_id', $order_id)->find();

        $app_order_info = db('app_order')->where(['app_order_project_id' => $order_id])->find();

        $list = $this->getOrdercommonInfo(array('order_id' => $project_order['order_id']));

        //追加返回订单扩展表信息
        $project_order['extend_order_common'] = db('orderproject_goods')->where(['order_id' => $order_id])->select();


        $project_order['extend_order_common']['reciver_info'] = unserialize($project_order['reciver_info']);

        // $project_order['extend_order_common']['invoice_info'] = unserialize($project_order['extend_order_common']['invoice_info']);

        //取商品列表
        $project_order['extend_order_goods'] = db('orderproject_goods')->where('order_id', $project_order['order_id'])->select();
        $this->assign('order_status', ['0' => '已取消', '10' => '未付款', '20' => '已付款', '30' => '已收货', '40' => '已完成', '50' => '已取消', '55' => '已作废', '60' => '已发货']);
        $this->assign('order_list', $project_order);

        $this->assign('order_id', $order_id);
        $this->assign('project_id', $project_order['project_id']);
        $this->assign('app_order_mall_id', $app_order_info['app_order_id']);
        return $this->fetch('projectorder_list');
    }

    //子订单详情
    public function view_band_goods()
    {
        $order_id = intval(input('param.order_id'));

        $project_order = db('orderproject_goods')->where('order_id', $order_id)->select();
        foreach ($project_order as $key => $value) {
            $goods_info = db('goods')->where(['goods_id' => $value['goods_id']])->find();
            $project_order[$key]['gu_final_price'] = $goods_info['gu_final_price'];
        }
        $this->assign('project_order', $project_order);
        return $this->fetch('view_band_goods');
    }

    public function getOrdercommonInfo($condition = array(), $field = '*')
    {
        $tblname = 'ordercommon';
        $field = 'a.*,b.orderproject_id,c.order_id';
        $orderproject = db($tblname . ' a')
            ->join('__ORDER__ b', 'a.order_id=b.order_id')
            ->join('__ORDERPROJECT__ c', 'b.orderproject_id=c.order_id')
            ->field($field)
            ->find();
        return $orderproject;
    }

    /**
     * 平台退款大订单
     *
     */
    public function refund_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        #更新项目定制订单表，更新商城订单表
        $order_info = db('order')->where('order_id', $order_id)->find();

        $res = db('order')->where('orderproject_id', $order_id)->data(['refund_state' => '3', 'order_state' => '50'])->update();

        $res2 = db('orderproject')->where('order_id', $order_id)->data(['refund_state' => '3', 'order_state' => '50', 'evaluation_state' => 1])->update();

        if ($res2) {
            ds_json_encode(10000, '操作成功');
        } else {
            ds_json_encode(10001, '操作失败');
        }
    }

    //商品管理
    public function project_goods()
    {
        $brand_model = model('goodproject');

        if (request()->isPost()) {
            $data = [
                'project_title' => input('post.project_title'),
            ];
            $brand_validate = validate('Goodproject');
            if (!$brand_validate->scene('brand_add')->check($data)) {
                $this->error($brand_validate->getError());
            } else {
                $update_array = array();
                //上传图片
                $default_dir = BASE_UPLOAD_PATH . DS . ATTACH_PATH . '/membertag';
                $img = '';
                if (!empty($_FILES['project_images']['name'])) {
                    $file = request()->file('project_images');
                    $info = $file->rule('uniqid')->validate(['ext' => ALLOW_IMG_EXT])->move($default_dir);
                    if ($info) {
                        $img = $info->getFilename();
                    } else {
                        $this->error($file->getError());
                    }
                }

                $brand_info = $brand_model->getBrandInfo(array('project_id' => intval(input('post.project_id'))));

                $condition['project_id'] = input('post.project_id');
                $express_list = rkcache('goods', true);
                $update_array['goods_commonid'] = empty($express_list) ? $brand_info['goods_commonid'] : $express_list;
                $update_array['project_title'] = input('post.project_title');
                $update_array['project_describe'] = input('post.project_describe');
                $update_array['project_images'] = empty($img) ? $brand_info['project_images'] : $img;
                $update_array['status'] = input('post.status');


                $result = $brand_model->editBrand($condition, $update_array);
                dkcache('goods');
                if ($result) {
                    $this->log(lang('ds_add') . lang('brand_index_brand') . '[' . input('post.brand_name') . ']', 1);
                    $this->success('修改成功', url('Goodproject/index'));
                } else {
                    $this->error(lang('ds_common_save_fail'));
                }
            }
        } else {

            //项目定制标题id
            $project_id = input('param.project_id');
            $order_id = input('param.order_id');
            $this->assign('project_id', $project_id);
            $this->assign('order_id', $order_id);

            $goods = db('goodsproject')->where(['project_id' => $project_id])->find();
            $search_goods_name = trim(input('param.search_goods_name'));
            $store_name = trim(input('param.store_name'));
            if ($goods['goods_commonid']) {
                //数量
                // $this->assign('num', $goods['num']);
                //标题
                $this->assign('title', $goods['project_title']);
                //搜索条件
                $this->assign('search_brand_name', trim(input('param.search_brand_name')));

                //所有绑定商品的id
                $goods_info = explode(",", $goods['goods_commonid']);

                $goods_model = model('goods');
                /**
                 * 处理商品分类
                 */
                $choose_gcid = ($t = intval(input('param.choose_gcid'))) > 0 ? $t : 0;
                $gccache_arr = model('goodsclass')->getGoodsclassCache($choose_gcid, 3);
                $this->assign('gc_json', json_encode($gccache_arr['showclass']));
                $this->assign('gc_choose_json', json_encode($gccache_arr['choose_gcid']));
                /**
                 * 查询条件
                 */
                $where = array();
                //根据选中的id
                if (!empty($goods['goods_commonid'])) {
                    $where['goodscommon.goods_commonid'] = ['in', $goods_info];
                }
                $where = [
                    'goodsprojectnums.project_id' => $project_id
                ];
                //关键词

                if ($search_goods_name != '') {
                    $where['goods_name'] = array('like', '%' . $search_goods_name . '%');
                }
                //.供应商名称

                if ($store_name != '') {
                    $where['store_name'] = array('like', '%' . $store_name . '%');
                }

                //品牌
                $b_id = intval(input('param.b_id'));
                if ($b_id > 0) {
                    $where['brand_id'] = $b_id;
                }
                //分类
                if ($choose_gcid > 0) {
                    $where['gc_id_' . ($gccache_arr['showclass'][$choose_gcid]['depth'])] = $choose_gcid;
                }
                $where1['order_id'] = $order_id;
                $goods_list = db('orderproject_goods')->where($where1)->select();
                $this->assign('order_id', $order_id);
                $this->assign('goods_list', $goods_list);
                // 品牌
                $brand_list = model('brand')->getBrandPassedList(array());

                $this->assign('search', $where);
                $this->assign('brand_list', $brand_list);
            } else {
                $goods_list[] = [
                    'project_id' => '',
                    'project_title' => '',
                    'project_images' => '',
                    'project_describe' => '',
                    'goods_name' => '',
                    'status' => 1,
                ];
                $this->assign('title', $goods['project_title']);
                $this->assign('goods_list', $goods_list);
            }

            //商品列表
            $this->assign('search_goods_name', $search_goods_name);
            $this->assign('store_name', $store_name);
            $this->setAdminCurItem('project_goods');
            return $this->fetch('project_goods');
        }
    }


    //编辑数量
    public function num()
    {

        if (request()->isPost()) {
            $data = input('param.');
            if ($data['num'] <= 0) {
                dsLayerOpenSuccess('输入值不能小于0');
            }
            $this->assign('rec_id', $data['rec_id']);
            $goods_result = db('orderproject_goods')->where(['rec_id' => $data['rec_id']])->update(['goods_num' => $data['num']]);
            if ($goods_result) {
                dsLayerOpenSuccess('编辑成功');
            }
        } else {
            $rec_id = input('param.rec_id');
            $this->assign('rec_id', $rec_id);
            $result = db('orderproject_goods')->where(['rec_id' => $rec_id])->find();
            $this->assign('num', $result['goods_num']);
            return $this->fetch();
        }
    }

    ///删除商品
    public function goods_drop()
    {
        $rec_id = input('param.rec_id');
        $num = db('orderproject_goods')->where(['rec_id' => $rec_id,])->delete();
        ds_json_encode(10000, lang('ds_common_del_succ'));
    }


    /*
 增加项目定制订单商品
*/
    public function edit_band_goods()
    {
        $goods_model = model('goods');
        $brand_model = model('goodproject');
        if (request()->isPost()) {
            $data = input('post.goods_commonid/a');
            if (!empty($data)) {
                $order_id = input('post.order_id');
                $project_id = input('post.project_id');
                foreach ($data as $key => $value) {
                    $info[] = $value;
                }
                $projectgoods = db('orderproject_goods')->where(['order_id' => $order_id])->find();
                //                var_dump($result);
                //                die();
                //判断库里是否有数据
                foreach ($data as $k => $v) {
                    $result = db('goods')->where(['goods_commonid' => $v])->find();
                    $goods_spec = '';
                    if (!empty($result['goods_spec'])) {
                        $goods_spec = implode(",", unserialize($result['goods_spec']));
                    }
                    if ($result) {
                        $res = [
                            'order_id' => $order_id,
                            'project_name' => $projectgoods['project_name'],
                            'store_id' => $result['store_id'],
                            'goods_name' => $projectgoods['goods_name'],
                            'goods_id' => $result['goods_id'],
                            'goods_image' => 'http://33wang.douyinhot.com/' . $result['goods_image'],
                            'buyer_id' => $projectgoods['buyer_id'],
                            'goods_price' => $result['goods_price'],
                            'goods_num' => 1,
                            'buyer_name' => $projectgoods['buyer_name'],
                            'goods_spec' => $goods_spec,
                            'is_background_add' => 1
                        ];
                        db('orderproject_goods')->insert($res);
                    }
                }
                dsLayerOpenSuccess('导入成功');
            } else {
                dsLayerOpenSuccess('请选择需要导入的商品');
            }
        } else {
            $goods_model = model('goods');

            $project_id = input('param.project_id');
            $order_id = input('param.order_id');
            $this->assign('order_id', $order_id);

            $where['project_id'] = $project_id;
            $info = db('goodsproject')->where($where)->find();
            $this->assign('project_id', $project_id);

            $info = explode(',', $info['goods_commonid']);
            $this->assign('info', $info);

            if (!empty(input('param.search_brand_name'))) {
                $condition['goods_name'] = array('like', "%" . input('param.search_brand_name') . "%");
            }
            $this->assign('search_brand_name', trim(input('param.search_brand_name')));


            // ------------------------

            //$goods = db('goodscommon')->where($condition)->select();
            //foreach($goods as $key => $val){
            //$goods_info[$key]['goods_name'] = $val['goods_name'];
            // $goods_info[$key]['goods_commonid'] = $val['goods_commonid'];
            //}
            //$this->assign('goods_info', $goods_info);
            $goods_model = model('goods');
            /**
             * 处理商品分类
             */
            $choose_gcid = ($t = intval(input('param.choose_gcid'))) > 0 ? $t : 0;

            $gccache_arr = model('goodsclass')->getGoodsclassCache($choose_gcid, 3);
            $this->assign('gc_json', json_encode($gccache_arr['showclass']));
            $this->assign('gc_choose_json', json_encode($gccache_arr['choose_gcid']));
            /**
             * 查询条件
             */
            $where = array();
            //查询已经审核完成的商品
            //            $where['goods_state'] = '1';
            //            $where['goods_verify'] = '1';
            $where['goods_lock'] = '0';
            $where['goods_status'] = '1';
            //邹建伟
            // $where['goods_commonid'] = ['not in',$info];
            $where['goods.goods_id'] = ['not in', $info];
            //关键词
            $search_goods_name = trim(input('param.search_goods_name'));
            if ($search_goods_name != '') {
                $where['goods_name'] = array('like', '%' . $search_goods_name . '%');
            }
            //供应商
            $store_name = trim(input('param.store_name'));
            if ($store_name != '') {
                $where['store_name'] = array('like', '%' . $store_name . '%');
            }
            //分类查询
            $search_gc_id1 = input('get.search_gc_id1', '');
            $search_gc_id2 = input('get.search_gc_id2', '');
            $search_gc_id3 = input('get.search_gc_id3', '');
            if ($search_gc_id1) {
                $where['gc_id_1'] = ['eq', $search_gc_id1];
            }
            if ($search_gc_id2) {
                $where['gc_id_2'] = ['eq', $search_gc_id2];
            }
            if ($search_gc_id3) {
                $where['gc_id_3'] = ['eq', $search_gc_id3];
            }

            //品牌
            $b_id = intval(input('param.b_id'));
            if ($b_id > 0) {
                $where['brand_id'] = $b_id;
            }
            //分类
            // if ($choose_gcid > 0) {
            //     $where['gc_id_' . ($gccache_arr['showclass'][$choose_gcid]['depth'])] = $choose_gcid;
            // }

            // $goods_list = $goods_model->getGoodsCommonList($where, '*', 10, 'goods_commonid desc');
            $goods_list = $goods_model->getGoodsUnionLists($where, '*', '', '', 10);

            $this->assign('goods_list', $goods_list);
            $this->assign('search_goods_name', $search_goods_name);
            $this->assign('store_name', $store_name);
            $this->assign('choose_gcid', $choose_gcid);
            $this->assign('show_page', $goods_model->page_info->render());

            $storage_array = $goods_model->calculateStorage($goods_list);
            $this->assign('storage_array', $storage_array);

            // 品牌
            $brand_list = model('brand')->getBrandPassedList(array());

            $this->assign('search', $where);
            $this->assign('brand_list', $brand_list);

            //三级分类查询
            $class = new Goodsclass();
            $parent_class_list = $class->getGoodsclassList(['gc_parent_id' => 0]);
            $this->assign('class_list', $parent_class_list);
            return $this->fetch();
        }
    }

    /**
     * 平台订单删除订单 （作废）
     *
     */
    public function del_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $res1 = db('orderproject')->where('order_id', $order_id)->data(['is_cancel' => '1', 'order_state' => 55, 'evaluation_state' => '1'])->update();

        if ($res1) {
            ds_json_encode(10000, '操作成功');
        } else {
            ds_json_encode(10001, '操作失败');
        }
    }

    //    生成商品单
    public function create_goods()
    {
        $order_id = intval(input('param.order_id'));

        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $order_model = new \app\common\model\Order();

        #项目定制订单表
        $project_info = db('orderproject')->where('order_id', $order_id)->find();

        #项目定制订单扩展表
        $projectgoods_list = db('orderproject_goods')->where(['order_id' => $order_id])->select();

        #根据店铺id不同分类
        $store_cart_list = $this->_getStoreCartList($projectgoods_list);


        #将不同店铺的数据分开
        $free = 0; #运费
        $goods_price = 0; #商品总价
        $freight_price = 0; #运费总价
        $project_integral = $project_info['project_integral'] / count($store_cart_list);

        #平分优惠券金额

        if ($project_info['coupon']) {
            $voucher_price = $project_info['coupon'] / count($store_cart_list);
        } else {
            $voucher_price = 0;
        }

        //  echo $voucher_price;die;
        $project_address_info = db('address')->where(['address_id' => $project_info['address_id']])->find();
        foreach ($store_cart_list as $store_id => $goods_list) {
            #获取店铺信息
            $store_info = db('store')->where(['store_id' => $store_id])->find();
            #生成商品订单
            $order['order_sn'] = $project_info['order_sn'];
            $order['pay_sn'] = $project_info['pay_sn'];
            $order['buyer_id'] = $project_info['buyer_id'];
            $order['buyer_name'] = $project_info['buyer_name'];
            $order['buyer_email'] = $project_info['buyer_email'];
            $order['store_id'] = $store_id;
            $order['store_name'] = $store_info['store_name'];
            $order['add_time'] = time();
            $order['payment_code'] = $project_info['payment_code'];
            $order['payment_time'] = $project_info['payment_time'];
            $order['order_state'] = $project_info['order_state'];
            $order['order_from'] = $project_info['order_from'];
            #商品总价
            $order['goods_amount'] = 0;
            #订单总价
            $order['order_amount'] = $project_info['order_amount'];
            $order['order_integral'] = $project_integral;
            #订单类型
            $order['order_type'] = 3;
            $order['orderproject_id'] = $project_info['order_id'];
            $order['yys_id'] = $project_info['yys_id'];
            $order['yys_name'] = $project_info['yys_name'];
            $order['order_voucher'] = $voucher_price;

            $order_mall_id = db('order')->insertGetId($order);

            $order_info['order_id'] = $order_mall_id;
            $order_list[$order_mall_id] = $order_info;


            // #将主单id放入项目定制订单里面
            db('orderproject')->where(['order_id' => $order_id])->update(['order_mall_id' => $order_mall_id, 'goodsbill' => 1]);

            //4、生成订单扩展表信息  （用于发货）
            $order_common['order_id'] = $order_mall_id;
            $order_common['store_id'] = $store_id;
            $order_common['reciver_info'] = $project_info['reciver_info'];
            $order_common['reciver_name'] = $project_info['reciver_name'];
            $order_common['reciver_city_id'] = $project_info['reciver_city_id'];
            $order_model->addOrdercommon($order_common);

            $freight_array = [];
            #生成ordergoods
            foreach ($goods_list as $key => $value) {
                $goods_info = db('goods')->where(['goods_id' => $value['goods_id']])->find();

                #商品扩展表
                $ordergoods['order_id'] = $order_mall_id;
                $ordergoods['goods_id'] = $value['goods_id'];
                $ordergoods['goods_name'] = $value['goods_name'];
                $ordergoods['goods_price'] = $goods_info['goods_price'];
                $ordergoods['goods_num'] = $value['goods_num'];
                $ordergoods['goods_image'] = $goods_info['goods_image'];
                $ordergoods['goods_pay_price'] = 0;
                $ordergoods['store_id'] = $store_id;
                $ordergoods['buyer_id'] = $project_info['buyer_id'];
                $ordergoods['goods_pay_price'] = $goods_info['goods_price'];
                $ordergoods['goods_original_price'] = $goods_info['goods_price'];  #供应商给平台的价格（展示在供应商）
                $ordergoods_id = db('ordergoods')->insertGetId($ordergoods);

                #商品总价(供应商给平台的价格)
                $goods_price += ($goods_info['goods_price'] * $value['goods_num']);
                #计算运费


                //  {“6”:[{“goods_id”:”65”,”is_home”:0,”is_to_pay”:0,”count”:2}]}

                $freight_array[$store_id][$key]['goods_id'] = $value['goods_id'];
                $freight_array[$store_id][$key]['count'] = $value['goods_num'];
                $freight_array[$store_id][$key]['is_to_pay'] = 0;

                if ($goods_info['waybill_type'] == 1 || $goods_info['waybill_type'] == 3) {
                    $freight_array[$store_id][$key]['is_home'] = 1;
                } else {
                    $freight_array[$store_id][$key]['is_home'] = 0;
                }
            }


            $freight_list = GoodsService::getInstance()->calculateFreight(array(), $project_address_info['area_id'], $freight_array);

            $order_amount = $freight_list['0']['shop_sum_freight'] + $goods_price;

            $freight_content = json_encode($freight_list['0']);
            db('order')->where(['order_id' => $order_mall_id])->data(['freight_content' => $freight_content, 'shipping_fee' => $freight_list['0']['shop_sum_freight'], 'order_amount' => $order_amount, 'goods_amount' => $goods_price])->update();

            #运费总价
            $freight_price += $freight_list['0']['shop_sum_freight'];
        }
        #生成大订单 
        $order_ids_array = array_keys($order_list);
        $order_ids = implode(',', $order_ids_array);
        $total['order_ids'] = $order_ids;

        $order_goods_info = db('ordergoods')->where('order_id', 'in', $order_ids)->select();

        if (!empty($order_goods_info)) {
            $total['goods_ids'] = implode(',', array_column($order_goods_info, 'goods_id'));
            $total['ordergoods_ids'] = implode(',', array_column($order_goods_info, 'rec_id'));
        }

        $project_address_info = db('address')->where(['address_id' => $project_info['address_id']])->find();

        $total['price'] = 0;
        #订单总额  （商品的总价 + 运费）
        $total['project_price'] = $free + $goods_price;
        $total['goods_prices'] = $goods_price;  #商品总价
        $total['order_status'] = 1;
        $total['app_order_type'] = 2;
        $total['freight'] = $freight_price;
        $total['order_sn'] = time() . '123';
        $total['pay_sn'] = $project_info['pay_sn'];
        $total['create_time'] = time();
        $total['user_id'] = $project_info['buyer_id'];
        $total['member_name'] = $project_info['buyer_name'];

        $total['phone'] = $project_address_info['address_tel_phone'];
        $total['user_name'] = $project_address_info['address_realname'];
        $total['user_address'] = $project_address_info['address_detail'];

        $total['app_order_project_id'] = $order_id;

        //下单使用了多少积分
        $total['use_integral'] = $project_info['order_integral'];

        //下单使用优惠劵优惠了多少钱
        $total['voucher_price'] = $project_info['coupon'];

        $total['voucher_id'] = $project_info['coupon_id'];


        $total['goods_project_price'] = $project_info['order_amount'];

        db('app_order')->data($total)->insert();
        $Id = db('app_order')->getLastInsID();


        foreach ($order_ids_array as $k => $v) {
            db('order')->data(['apporder_id' => $Id])->where(['order_id' => $v])->update();
        }


        #shen  处理分账
        $app_order_info = db('app_order')->where('app_order_id', $Id)->find();

        $order_list = db('order')->where('apporder_id', $Id)->select();
        //p($order_list);die;
        $store_info = db('store')->where('store_id', $order_list['0']['yys_id'])->find();
        if ($order_list) {

            if ($app_order_info['voucher_id']) {
                $voucher_info = db('voucher')->where('voucher_id', $app_order_info['voucher_id'])->find();
            }


            foreach ($order_list as $k => $v) {
                $update_data = [];
                $g_profit_content = [];
                $y_profit_content = [];
                $p_profit_content = [];
                #总利润
                #供应商
                $update_data['g_profit'] = $v['goods_amount'] + $v['shipping_fee'];
                $g_profit_content['goods_amount'] = $v['goods_amount'];
                $g_profit_content['shipping_fee'] = $v['shipping_fee'];
                $update_data['g_profit_content'] = json_encode($g_profit_content);

                #运营商
                $update_data['y_profit'] = ($app_order_info['goods_project_price'] - $app_order_info['freight'] - $app_order_info['goods_prices']) * $store_info['deduct_project'] / 100;
                $y_profit_content['goods_project_price'] = $app_order_info['goods_project_price'];
                $y_profit_content['deduct_project'] = $store_info['deduct_project'];
                $y_profit_content['freight'] = $app_order_info['freight'];
                $y_profit_content['goods_prices'] = $app_order_info['goods_prices'];
                $update_data['y_profit_content'] = json_encode($y_profit_content);
                #平台
                $update_data['p_profit'] = $app_order_info['goods_project_price'] - $app_order_info['freight'] - $app_order_info['goods_prices'] - $update_data['y_profit'];
                $p_profit_content['goods_project_price'] = $app_order_info['goods_project_price'];
                $p_profit_content['deduct_project'] = $store_info['deduct_project'];
                $p_profit_content['freight'] = $app_order_info['freight'];
                $p_profit_content['goods_prices'] = $app_order_info['goods_prices'];
                $p_profit_content['y_profit'] = $update_data['y_profit'];
                $update_data['p_profit_content'] = json_encode($p_profit_content);

                $p_share_content = [];
                $g_share_content = [];
                $y_share_content = [];
                #总分担
                #优惠券
                if (isset($voucher_info) && $voucher_info) {
                    $p_share_content['is_voucher'] = 1;
                    $g_share_content['is_voucher'] = 1;
                    $y_share_content['is_voucher'] = 1;

                    $p_share_content['voucher_content'] = json_encode($voucher_info);
                    $g_share_content['voucher_content'] = json_encode($voucher_info);
                    $y_share_content['voucher_content'] = json_encode($voucher_info);

                    $g_voucher = $v['order_voucher'] * $voucher_info['g_ratio'] / 100;
                    $y_voucher = $v['order_voucher'] * $voucher_info['y_ratio'] / 100;
                    $p_voucher = $v['order_voucher'] * $voucher_info['z_ratio'] / 100;
                } else {
                    $p_share_content['is_voucher'] = 0;
                    $g_share_content['is_voucher'] = 0;
                    $y_share_content['is_voucher'] = 0;

                    $p_share_content['voucher_content'] = '';
                    $g_share_content['voucher_content'] = '';
                    $y_share_content['voucher_content'] = '';

                    $g_voucher = 0;
                    $y_voucher = 0;
                    $p_voucher = 0;
                }
                #积分
                if ($v['order_integral']) {
                    $p_share_content['is_score'] = 1;
                    $p_share_content['score_content'] = $app_order_info['use_integral_text'];
                    $p_score = $v['order_integral'];
                } else {
                    $p_score = 0;
                }
                #总分担
                $update_data['g_share_money'] = round($g_voucher, 2);
                $update_data['y_share_money'] = round($y_voucher, 2);
                $update_data['p_share_money'] = round(($p_voucher + $p_score), 2);

                $update_data['p_share_content'] = json_encode($p_share_content);
                $update_data['y_share_content'] = json_encode($y_share_content);
                $update_data['g_share_content'] = json_encode($g_share_content);

                #最后可得
                $update_data['p_price'] = $update_data['p_profit'] - $update_data['p_share_money'];
                $update_data['y_price'] = $update_data['y_profit'] - $update_data['y_share_money'];
                $update_data['g_price'] = $update_data['g_profit'] - $update_data['g_share_money'];

                db('order')->where('order_id', $v['order_id'])->data($update_data)->update();
            }
        }
        return json(['url' => url('Projectorder/index'), 'code' => 1, 'msg' => '生成成功']);
    }

    //生成服务单
    public function generate_service_single()
    {
        if (request()->isPost()) {
            #生成服务单
            $data = input('post.');

            #获取项目定制订单信息
            $project_data = db('orderproject')->where(['order_id' => $data['order_id']])->find();
            //找到缓冲表
            $service_project_info = db('s_project_service_goods')->where(['order_id' => $data['order_id']])->select();

            $service_price = '';#服务单价格
            #生成服务主单
            $service_data = [
                'order_sn' => $this->makeOrderSn(),
                'pay_sn' => $project_data['pay_sn'],
                'order_type' => 1,
                'order_source' => 2,
                'member_id' => $project_data['buyer_id'],
                'member_name' => $project_data['buyer_name'],
                'assign_mechanic_total' => $data['need_hours'] * $data['fuwu_hour'] + $data['door_fee'],#给服务人员的总价格
                'door_fee' => $data['door_fee'],
                'order_amount' => $data['need_hours'] * $data['fuwu_hour'] + $data['door_fee'],
                'pay_amount' => $data['need_hours'] * $data['fuwu_hour'] + $data['door_fee'],
                'work_master_hous' => $data['need_hours'],
                'work_master_price' => $data['need_hours'] * $data['fuwu_hour'],
                'order_state' => 3,
                'payment_code' => 'alipay_app',
                'payment_time' => $project_data['payment_time'],
                'appointment_time' => $data['appointment_time'],
                'appointment_unix_time' => strtotime($data['appointment_time']),
                'add_time' => time(),
                'remarks' => $data['remarks'],
                'service_content' => $data['service_content'],
                'address_id' => $project_data['address_id'],
                'appoint_phone' => $project_data['phone'],
                'appoint_address' => $project_data['user_address'],
                'appoint_detail_address' => $project_data['user_address'],
            ];
            $service_price = $data['need_hours'] * $data['fuwu_hour'] + $data['door_fee'];
            $orderId = db('s_order')->insertGetId($service_data);
      
            #生成服务详情单
            foreach ($service_project_info as $k => $v) {
                $detailInfo = array(
                    'order_id' => $orderId,
                    'place_type' => 1,
                    'disma_status' => 2,
                    'goods_id' => $v['goods_id'],
                    'gc_id' => $v['gc_id'],
                    'gc_one_id' => $v['gc_id_1'],
                    'gc_two_id' => $v['gc_id_2'],
                    'gc_three_id' => $v['gc_id_3'],
                    'class_name' => $v['class_name'],
                    'goods_name' => $v['goods_name'],
                    'b_name' => $v['brand_name'],
                    'type_model' => $v['goods_spec'],
                    'add_time' => time(),
                );
                db('s_order_detail')->insertGetId($detailInfo);
            }
            //删除缓冲表数据
            db('s_project_service_goods')->where(['order_id' => $data['order_id']])->delete();

            //修改项目定制表的数据
            if(!empty($project_data['service_id'])){
                $orderId = $project_data['service_id'] .','. $orderId;
            }
            if(!empty($project_data['service_price'])){
                $service_price = $project_data['service_price'] + $service_price;
            }
            db('orderproject')->where(['order_id'=>$data['order_id']])->update(['service_id'=>$orderId,'service_price' =>$service_price]);
            
            if (!$orderId) {
                dsLayerOpenSuccess('操作失败');
            } else {
                dsLayerOpenSuccess('操作成功');
            }

        } else {
            $order_id = intval(input('param.order_id'));    #项目定制订单id
            $project_id = intval(input('param.project_id')); #项目定制的id

            $project_order = db('orderproject')->alias('op')
                ->where('order_id', $order_id)->find();

            $app_order_info = db('app_order')->where(['app_order_project_id' => $order_id])->find();

            //追加返回订单扩展表信息
            $project_order['extend_order_common'] = db('orderproject_goods')->where(['order_id' => $order_id])->select();
            $project_order['extend_order_common']['reciver_info'] = unserialize($project_order['reciver_info']);

            //取商品列表
            $project_order['extend_order_goods'] = db('orderproject_goods')->where('order_id', $project_order['order_id'])->select();

            //用于缓冲表
            $project_order['extend_project_service_goods'] = db('s_project_service_goods')->where('order_id', $order_id)->select();

            $this->assign('order_status', ['0' => '已取消', '10' => '未付款', '20' => '已付款', '30' => '已收货', '40' => '已完成', '50' => '已取消', '55' => '已作废', '60' => '已发货']);
            $this->assign('order_list', $project_order);

            $this->assign('order_id', $order_id);
            $this->assign('project_id', $project_id);
            $this->assign('app_order_mall_id', $app_order_info['app_order_id']);
            return $this->fetch('generate_service_single');
        }
    }

    //生成服务单导入设备
    public function service_goods()
    {
        $goods_model = model('goods');
        $brand_model = model('goodproject');
        if (request()->isPost()) {
            $data = input('post.goods_id/a');
            if (!empty($data)) {
                $order_id = input('post.order_id');
                $project_id = input('post.project_id');
                foreach ($data as $key => $value) {
                    $info[] = $value;
                }
                $projectgoods = db('orderproject_goods')->where(['order_id' => $order_id])->find();

                //判断库里是否有数据
                foreach ($data as $k => $v) {
                    $result = db('goods')->where(['goods_id' => $v])->find();
                    $brand_info = db('brand')->where(['brand_id'=>$result['brand_id']])->find();  

                    $goods_spec = '';
                    if (!empty($result['goods_spec'])) {
                        $goods_spec = implode(",", unserialize($result['goods_spec']));
                    }
                    if ($result) {
                        $res = [
                            'order_id' => $order_id,
                            'project_id' => $project_id,
                            'store_id' => $result['store_id'],
                            'goods_name' => $result['goods_name'],
                            'goods_id' => $result['goods_id'],
                            'goods_image' => 'http://33wang.douyinhot.com/' . $result['goods_image'],
                            'buyer_id' => $projectgoods['buyer_id'],
                            'goods_price' => $result['goods_price'],
                            'goods_num' => 1,
                            'buyer_name' => $projectgoods['buyer_name'],
                            'goods_spec' => $goods_spec,
                            'brand_name' => $brand_info['brand_name'],
                        ];
                        //处理分类
                        $class = db('goodsclass')->where(['gc_id' => $result['gc_id']])->find();
                        if (empty($class['gc_parent_id'])) {
                            //没父值的话就是一级分类id
                            $res['gc_id_1'] = $class['gc_id'];
                            $res['gc_id'] = $class['gc_id'];
                            $res['class_name'] = $class['gc_name'];
                        } else {
                            //有父值的话再往上找
                            $class_one = db('goodsclass')->where(['gc_id' => $class['gc_parent_id']])->find();
                            if (empty($class_one['gc_parent_id'])) {
                                $res['gc_id_1'] = $class_one['gc_id'];
                                $res['gc_id_2'] = $class['gc_id'];
                                $res['gc_id'] = $class['gc_id'];
                                $res['class_name'] = $class_one['gc_name'] . '>' . $class['gc_name'];
                            } else {
                                $class_two = db('goodsclass')->where(['gc_id' => $class_one['gc_parent_id']])->find();
                                $res['gc_id_1'] =  $class_two['gc_id'];
                                $res['gc_id_2'] =  $class_one['gc_id'];
                                $res['gc_id_3'] = $class['gc_id'];
                                $res['gc_id'] = $class['gc_id'];
                                $res['class_name'] = $class_two['gc_name'] . '>' . $class_one['gc_name'] . '>' . $class['gc_name'];
                            }
                        }

                        db('s_project_service_goods')->insert($res);
                    }
                }
                dsLayerOpenSuccess('导入成功');
            } else {
                dsLayerOpenSuccess('请选择需要导入的商品');
            }
        } else {
            $goods_model = model('goods');

            $project_id = input('param.project_id');
            $order_id = input('param.order_id');
            $this->assign('order_id', $order_id);
            $this->assign('project_id', $project_id);

            $where['project_id'] = $project_id;
            $info = db('goodsproject')->where($where)->find();
            $this->assign('project_id', $project_id);

            $info = explode(',', $info['goods_commonid']);
            $this->assign('info', $info);

            if (!empty(input('param.search_brand_name'))) {
                $condition['goods_name'] = array('like', "%" . input('param.search_brand_name') . "%");
            }
            $this->assign('search_brand_name', trim(input('param.search_brand_name')));


            // ------------------------
            $goods_model = model('goods');
            /**
             * 处理商品分类
             */
            $choose_gcid = ($t = intval(input('param.choose_gcid'))) > 0 ? $t : 0;

            $gccache_arr = model('goodsclass')->getGoodsclassCache($choose_gcid, 3);
            $this->assign('gc_json', json_encode($gccache_arr['showclass']));
            $this->assign('gc_choose_json', json_encode($gccache_arr['choose_gcid']));
            /**
             * 查询条件
             */
            $where = array();

            $where['goods_lock'] = '0';
            $where['goods_status'] = '1';
            //邹建伟
            // $where['goods_commonid'] = ['not in',$info];
            $where['goods.goods_id'] = ['not in', $info];
            //关键词
            $search_goods_name = trim(input('param.search_goods_name'));
            if ($search_goods_name != '') {
                $where['goodscommon.goods_name'] = array('like', '%' . $search_goods_name . '%');
            }
            //供应商
            $store_name = trim(input('param.store_name'));
            if ($store_name != '') {
                $where['goodscommon.store_name'] = array('like', '%' . $store_name . '%');
            }
            //分类查询
            $search_gc_id1 = input('get.search_gc_id1', '');
            $search_gc_id2 = input('get.search_gc_id2', '');
            $search_gc_id3 = input('get.search_gc_id3', '');
            if ($search_gc_id1) {
                $where['goodscommon.gc_id_1'] = ['eq', $search_gc_id1];
            }
            if ($search_gc_id2) {
                $where['goodscommon.gc_id_2'] = ['eq', $search_gc_id2];
            }
            if ($search_gc_id3) {
                $where['goodscommon.gc_id_3'] = ['eq', $search_gc_id3];
            }

            //品牌
            $b_id = intval(input('param.b_id'));
            if ($b_id > 0) {
                $where['brand_id'] = $b_id;
            }
            // $goods_list = $goods_model->getGoodsCommonList($where, '*', 10, 'goods_commonid desc');
            $goods_list = $goods_model->getGoodsProjectLists($where, '*', '', '', 10);
           // p($goods_list);die;
            $this->assign('goods_list', $goods_list);
            $this->assign('search_goods_name', $search_goods_name);
            $this->assign('store_name', $store_name);
            $this->assign('choose_gcid', $choose_gcid);
            $this->assign('show_page', $goods_model->page_info->render());

            $storage_array = $goods_model->calculateStorage($goods_list);
            $this->assign('storage_array', $storage_array);
            // 品牌
            $brand_list = model('brand')->getBrandPassedList(array());

            $this->assign('search', $where);
            $this->assign('brand_list', $brand_list);

            //三级分类查询
            $class = new Goodsclass();
            $parent_class_list = $class->getGoodsclassList(['gc_parent_id' => 0]);
            $this->assign('class_list', $parent_class_list);
            return $this->fetch();
        }
    }

    /**
     * 系统取消订单
     */
    private function _order_cancel($order_info)
    {
        $order_id = $order_info['order_id'];
        $order_model = model('order');
        $logic_order = model('order', 'logic');
        $if_allow = $order_model->getOrderOperateState('system_cancel', $order_info);
        if (!$if_allow) {
            return ds_callback(false, lang('no_right_operate'));
        }
        $result = $logic_order->changeOrderStateCancel($order_info, 'system', $this->admin_info['admin_name']);
        if ($result['code']) {
            $this->log(lang('order_log_cancel') . ',' . lang('ds_order_sn') . ':' . $order_info['order_sn'], 1);
        }
        return $result;
    }


    /**
     * 系统收到货款
     * @throws Exception
     */
    private function _order_receive_pay($order_info, $post)
    {
        $order_id = $order_info['order_id'];
        $order_model = model('order');
        $logic_order = model('order', 'logic');
        $if_allow = $order_model->getOrderOperateState('system_receive_pay', $order_info);
        if (!$if_allow) {
            return ds_callback(false, lang('no_right_operate'));
        }

        if (!request()->isPost()) {
            $this->assign('order_info', $order_info);
            //显示支付接口列表
            $payment_list = model('payment')->getPaymentOpenList();
            //去掉预存款和货到付款
            foreach ($payment_list as $key => $value) {
                if ($value['payment_code'] == 'predeposit' || $value['payment_code'] == 'offline') {
                    unset($payment_list[$key]);
                }
            }
            $this->assign('payment_list', $payment_list);
            echo $this->fetch('receive_pay');
            exit;
        } else {
            $order_list = $order_model->getOrderList(array('pay_sn' => $order_info['pay_sn'], 'order_state' => ORDER_STATE_NEW));
            $result = $logic_order->changeOrderReceivePay($order_list, 'system', $this->admin_info['admin_name'], $post);
            if ($result['code']) {
                $this->log('将订单改为已收款状态,' . lang('ds_order_sn') . ':' . $order_info['order_sn'], 1);
            }
            return $result;
        }
    }

    /**
     * 系统处理发票
     * @throws
     */
    public function invoice_state()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error('操作失败');
        }
        if (!request()->isPost()) {
            //            $invoice_info = db('invoice')->where('app_order_id',$order_id)->find();
            $tblname = 'invoice';
            $field = 'a.*,b.name,b.type,b.billing_type';
            $where['a.app_order_id'] = $order_id;
            $where['b.status'] = 1;
            $where['b.is_del'] = 0;
            $invoice_info = db($tblname . ' a')->join('__INVOICE_TYPE__ b', 'a.invoice_type_id=b.id')->where($where)->field($field)->find();
            //获取发票类型
            if (!empty($invoice_info['invoice_type_id'])) {
                $invoice_type_info = db('invoice_type')->where(['id' => $invoice_info['invoice_type_id']])->find();
                $this->assign('invoice_type_info', $invoice_type_info);
            }
            if (empty($invoice_info)) {
                $this->error('操作失败');
            }
            $app_order_info = db('app_order')->where('app_order_id', $order_id)->find();
            $order_info = db('order')->where('order_id', '10')->find();
            if (empty($app_order_info)) {
                $this->error('操作失败');
            }
            $this->assign('invoice_info', $invoice_info);
            $this->assign('app_order_info', $app_order_info);
            $this->assign('order_info', $order_info);
            return $this->fetch('invoice_state');
        } else {
            $order_id = intval(input('param.app_order_id'));
            if ($order_id <= 0) {
                $this->error('操作失败');
            }
            $status = intval(input('param.status'));
            $invoice_state = intval(input('param.invoice_state'));
            if ($status == 1) {
                #成功
                $data['invoice_logistics'] = input('post.code', '');
                $data['invoice_status'] = '2';
            } else {
                $data['invoice_no_content'] = input('post.no_content');
                $data['invoice_status'] = '3';
            }

            $res = db('app_order')->where('app_order_id', $order_id)->data($data)->update();
            if (!$res) {
                dsLayerOpenSuccess('操作失败');
            } else {
                dsLayerOpenSuccess('操作成功');
            }
        }
    }

    /**
     * 查看订单
     *
     */
    public function show_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $order_model = model('order');
        $order_info = $order_model->getOrderInfo(array('order_id' => $order_id), array('order_goods', 'order_common', 'store'));

        //订单变更日志
        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        $this->assign('order_log', $log_list);

        //退款退货信息
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['order_id'] = $order_info['order_id'];
        $condition['seller_state'] = 2;
        // $condition['admin_time'] = array('gt', 0);
        $return_list = $refundreturn_model->getReturnList($condition);
        $this->assign('return_list', $return_list);

        //退款信息
        $refund_list = $refundreturn_model->getRefundDaList($condition);
        $this->assign('refund_list', $refund_list);

        //卖家发货信息
        if (!empty($order_info['extend_order_common']['daddress_id'])) {
            $daddress_info = model('daddress')->getAddressInfo(array('daddress_id' => $order_info['extend_order_common']['daddress_id']));
            $this->assign('daddress_info', $daddress_info);
        }
        $this->assign('order_info', $order_info);
        return $this->fetch('show_order');
    }

    /**
     * 导出
     *
     */
    public function export_step1()
    {

        $order_model = model('order');
        $condition = array();
        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['order_sn'] = $order_sn;
        }
        $store_name = input('param.store_name');
        if ($store_name) {
            $condition['store_name'] = $store_name;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '10', '20', '30', '40'))) {
            $condition['order_state'] = $order_state;
        }
        $payment_code = input('param.payment_code');
        if ($payment_code) {
            $condition['payment_code'] = $payment_code;
        }
        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['buyer_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }

        if (!is_numeric(input('param.curpage'))) {
            $count = $order_model->getOrderCount($condition);
            $export_list = array();
            if ($count > self::EXPORT_SIZE) { //显示下载链接
                $page = ceil($count / self::EXPORT_SIZE);
                for ($i = 1; $i <= $page; $i++) {
                    $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                    $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                    $export_list[$i] = $limit1 . ' ~ ' . $limit2;
                }
                $this->assign('export_list', $export_list);
                return $this->fetch('/public/excel');
            } else { //如果数量小，直接下载
                $data = $order_model->getOrderList($condition, '', '*', 'order_id desc', self::EXPORT_SIZE);
                $this->createExcel($data);
            }
        } else { //下载
            $limit1 = (input('param.curpage') - 1) * self::EXPORT_SIZE;
            $limit2 = self::EXPORT_SIZE;
            $data = $order_model->getOrderList($condition, '', '*', 'order_id desc', "{$limit1},{$limit2}");
            $this->createExcel($data);
        }
    }

    /**
     * 生成excel
     *
     * @param array $data
     */
    private function createExcel($data = array())
    {
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/export.lang.php');
        $excel_obj = new \excel\Excel();
        $excel_data = array();
        //设置样式
        $excel_obj->setStyle(array('id' => 's_title', 'Font' => array('FontName' => '宋体', 'Size' => '12', 'Bold' => '1')));
        //header
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_no'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_store'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_buyer'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_xtimd'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_count'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_yfei'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_paytype'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_state'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_storeid'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_buyerid'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_bemail'));
        //data
        foreach ((array) $data as $k => $v) {
            $tmp = array();
            $tmp[] = array('data' => 'DS' . $v['order_sn']);
            $tmp[] = array('data' => $v['store_name']);
            $tmp[] = array('data' => $v['buyer_name']);
            $tmp[] = array('data' => date('Y-m-d H:i:s', $v['add_time']));
            $tmp[] = array('format' => 'Number', 'data' => ds_price_format($v['order_amount']));
            $tmp[] = array('format' => 'Number', 'data' => ds_price_format($v['shipping_fee']));
            $tmp[] = array('data' => get_order_payment_name($v['payment_code']));
            $tmp[] = array('data' => get_order_state($v));
            $tmp[] = array('data' => $v['store_id']);
            $tmp[] = array('data' => $v['buyer_id']);
            $tmp[] = array('data' => $v['buyer_email']);
            $excel_data[] = $tmp;
        }
        $excel_data = $excel_obj->charset($excel_data, CHARSET);
        $excel_obj->addArray($excel_data);
        $excel_obj->addWorksheet($excel_obj->charset(lang('exp_od_order'), CHARSET));
        $excel_obj->generateXML($excel_obj->charset(lang('exp_od_order'), CHARSET) . input('param.curpage') . '-' . date('Y-m-d-H', time()));
    }

    /**
     * 将下单商品列表转换为以店铺ID为下标的数组
     *
     * @param array $cart_list
     * @return array
     */
    private function _getStoreCartList($projectgoods_list)
    {
        if (empty($projectgoods_list) || !is_array($projectgoods_list))
            return $projectgoods_list;
        $new_array = array();
        foreach ($projectgoods_list as $cart) {
            $new_array[$cart['store_id']][] = $cart;
        }
        return $new_array;
    }
    private function makeOrderSn()
    {
        $date = date('Ymd');
        $num = $date . '0000' . substr(time(), 3, 7) . rand(1000, 999);

        return $num;
    }


    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'index',
                'text' => '待发货订单',
                'url' => url('projectorder/index')
            ),
            array(
                'name' => 'index2',
                'text' => '订单记录',
                'url' => url('projectorder/index2')
            ),
            // array(
            //     'name' => 'invoice_list',
            //     'text' => '审核通过发票',
            //     'url' => url('Order/invoice_list')
            // ),
        );
        return $menu_array;
    }
}
